<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

/**
 * @AutoController()
 * Class UploadController
 * @package App\Controller
 */
class UploadController
{
    /**
     * @PostMapping()
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return \Psr\Http\Message\ResponseInterface
     * @author github_sw <github_sw@yeah.net>
     */
    public function upload(RequestInterface $request, ResponseInterface $response)
    {
        $type = $request->input('type') ?? 'file';
        if (!$request->hasFile($type)) {
            return $response->withStatus(500)->json(['code' => 500, 'msg' => '没有选择文件']);
        }

        if (!$request->file($type)->isValid()) {
            return $response->withStatus(500)->json(['code' => 500, 'msg' => '文件无效']);
        }

        $file        = $request->file('file');
        $extension   = $file->getExtension();
        $index_fornt = '/storage/uploads/' . $type . '/' . date('Ymd') . '/';
        $file_name   = uniqid() . '.' . $extension;

        creatMkdirs(BASE_PATH . $index_fornt);
        $file->moveTo(BASE_PATH . $index_fornt . $file_name);
        $url = praseUrl($request->url()) . $index_fornt . $file_name;

        // 通过 isMoved(): bool 方法判断方法是否已移动
        if ($file->isMoved()) {
            return $response->json(['code' => 200, 'msg' => '上传成功', 'data' => $url]);
        }
        return $response->withStatus(500)->json(['code' => 50, 'msg' => '上传失败']);
    }


}
